package com.dongdongshop.controller;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.dongdongshop.data.Result;
import com.dongdongshop.page.PageBean;
import com.dongdongshop.vo.ItemVO;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.index.query.MatchAllQueryBuilder;
import org.elasticsearch.index.query.MatchQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("es")
@RefreshScope
public class ESController {

    @Autowired
    private RestHighLevelClient client;

   /* //批量添加文档
    @PostMapping("bulkAdd")
    public String bulkAdd() throws IOException {
        BulkRequest bulkRequest = new BulkRequest();
//        bulkRequest.timeout("10s");
        *//*查询到数据之后就存到es的文档中去*//*
        List<TbSeckillGoods> goods = seckillService.getSeckillList();
        // 批量请求处理
        for (int i = 0; i < goods.size(); i++) {
            bulkRequest.add(
                    // 这里是数据信息
                    new IndexRequest("demo_index")
                            .id(""+(i + 1)) // 没有设置id 会自定生成一个随机id
                            .source(JSON.toJSONString(goods.get(i)), XContentType.JSON)
            );
        }
        BulkResponse bulk = restHighLevelClient.bulk(bulkRequest, RequestOptions.DEFAULT);
        System.out.println(bulk.status());// ok
        return "ok";
    }*/

    //聚合查询 并高亮显示查询结果
    @PostMapping("getPage")
    public Result getPage(@RequestParam String title, @RequestParam(defaultValue = "1", required = false) Integer pageNum, @RequestParam(defaultValue = "15", required = false) Integer pageSize) throws IOException {
        SearchRequest request = new SearchRequest();
        List<ItemVO> list = new ArrayList<>();
        request.indices(new String[]{"dongdongshop"});
        SearchSourceBuilder builder = new SearchSourceBuilder();
        if (!StrUtil.isNotBlank(title)) {
            MatchAllQueryBuilder queryBuilder = QueryBuilders.matchAllQuery();
            builder.from(pageNum);
            builder.size(pageSize);
            builder.query(queryBuilder);
        } else {
            MatchQueryBuilder query = QueryBuilders.matchQuery("title", title);
//            MatchQueryBuilder query2 = QueryBuilders.matchQuery("category", title);
//            MatchQueryBuilder query3 = QueryBuilders.matchQuery("sell_point", title);
            builder.from(pageNum);
            builder.size(pageSize);
            builder.query(query);
        }
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        highlightBuilder.preTags(new String[]{"<font color='red'>"});
        highlightBuilder.postTags(new String[]{"</font>"});
        highlightBuilder.field("title");
        builder.highlighter(highlightBuilder);
        request.source(builder);
        SearchResponse search = null;
        try {
            search = client.search(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            e.printStackTrace();
        }
        SearchHits hits = search.getHits();
        for (SearchHit hit : hits) {
            String sourceAsString = hit.getSourceAsString();
            Map<String, Object> sourceAsMap = hit.getSourceAsMap();
            //打印高亮结果
            Map<String, HighlightField> highlightFields = hit.getHighlightFields();
            HighlightField title1 = highlightFields.get("title");
            if (title1 != null) {
                Text[] fragments = title1.fragments();
                StringBuffer niwTitle = new StringBuffer();
                for (Text test : fragments) {
                    niwTitle.append(test);
                }
                sourceAsMap.put("title", niwTitle.toString());
            }
            ItemVO itemVO = JSONObject.parseObject(JSON.toJSONString(sourceAsMap), ItemVO.class);
            list.add(itemVO);
        }

        PageBean<ItemVO> pageBean = new PageBean<>();
        String s = String.valueOf(hits.getTotalHits());
        String[] s1 = s.split(" ");
        Long totalHits = Long.valueOf(s1[0]);
        System.out.println(totalHits);
        pageBean.setTotal(totalHits);
        pageBean.setPageSize(pageSize);
        pageBean.setPageNum(pageNum);
        pageBean.setRows(list);
        return Result.OK().setData(pageBean);
    }
}
